$(document).ready(function(){
	var ajaxQueueArray = [];
	var load = $('span#load').attr('url');

	(function($) {

	// jQuery on an empty object, we are going to use this as our Queue
	var ajaxQueue = $({});

	$.ajaxQueue = function( ajaxOpts ) {
		var jqXHR,
			dfd = $.Deferred(),
			promise = dfd.promise();

		// run the actual query
		function doRequest( next ) {
			jqXHR = $.ajax( ajaxOpts );
			jqXHR.done( dfd.resolve )
				.fail( dfd.reject )
				.then( next, next );
		}

		// queue our ajax request
		ajaxQueue.queue( doRequest );

		// add the abort method
		promise.abort = function( statusText ) {

			// proxy abort to the jqXHR if it is active
			if ( jqXHR ) {
				return jqXHR.abort( statusText );
			}

			// if there wasn't already a jqXHR we need to remove from queue
			var queue = ajaxQueue.queue(),
				index = $.inArray( doRequest, queue );

			if ( index > -1 ) {
				queue.splice( index, 1 );
			}

			// and then reject the deferred
			dfd.rejectWith( ajaxOpts.context || ajaxOpts, [ promise, statusText, "" ] );
			return promise;
		};

		return promise;
	};

	})(jQuery);
	
	var run = {
		init:function(e,key, kind, grade_type ,del){

			if(typeof e !== "undefined" || status == 'unprocessed'){
				jQuery.ajaxQueue({
					type: "POST",
					url: e.attr('url'),
					data:{
						option: grade_type === "smiley" ? e.attr("value") : e.val()
					}
				}).done(function(output){
					if(output == true){
						compute_attendance_total(kind);


						if(grade_type === "smiley"){
							e.parents('td').find('span.loading').html('<i class="icon-ok"></i>');
						}else{

							// compute_final_grade(e);
							e.siblings('span.loading').html('<i class="icon-ok"></i>');
						}
						
						if(del)
						{
							alert('Subject deleted from student.');
							e.parents('tr').hide('slow');
						}

						ajaxQueueArray[key] = {status : 'processed'};
					}else{

						if(grade_type === "smiley"){
							e.parents('td').find('span.loading').html('<i class="icon-remove"></i>');
						}else{
							e.siblings('span.loading').html('<i class="icon-remove"></i>');
						}
					}
				}).fail(function(){
					if(grade_type === "smiley"){
						e.parents('td').find('span.loading').html('<i class="icon-warning-sign"></i>');
					}else{
						e.siblings('span.loading').html('<i class="icon-warning-sign"></i>');
					}
				});
			}
		},
		holder: function(e){
			var _holder ={
					status : 'unprocessed',
					ajaxObject : e
			};
			
			ajaxQueueArray.push(_holder);
		}
	};
	
	$('input[type=text].ajax-change').on('blur',function()
	{
		var val = $(this).val();
		var orgval = $(this).attr('orgval');
		var kind = $(this).attr('kind');

		// if(val.length >= 2 && isInt(val))
		if(val.length >= 1)
		{	
		
			if(val !== orgval){
				$(this).siblings('span.loading').html('<img src="'+load+'">');
				$(this).attr('orgval',val);
				//create a holder for objects
				ajaxQueueArray = [];
				run.holder($(this));
				
				// console.log(ajaxQueue);
				//loop
				$.each(ajaxQueueArray,function(i,e)
				{	
					if(e.status == 'unprocessed')
					{
						run.init(e.ajaxObject,i, kind);
					}
				});
			}
			
		}else{
			$(this).siblings('span.loading').html('<i class="icon-pencil"></i>');
		}
	});
	
	$('a.ajax-del_subject').on('click',function()
	{
		var eid = $(this).attr("e_id");
		var val = $(this).attr('value').trim();
		//var orgval = $(this).attr('orgval').trim();
		//console.log(orgval);
		// if(val.length >= 2 && isInt(val))
		//if(val.length >= 1)
		//{	
		
			//if(val !== orgval){
				$(this).siblings('span.loading').html('<img src="'+load+'">');
				//$(this).attr('orgval',val);
				//create a holder for objects
				ajaxQueueArray = [];
				run.holder($(this));
				
				// console.log(ajaxQueue);
				//loop
				$.each(ajaxQueueArray,function(i,e)
				{	
					if(e.status == 'unprocessed')
					{
						run.init(e.ajaxObject,i, "", "", del=true);
					}
				});
			//}
			
		//}else{
			//$(this).parents('td').find('span.loading').html('<i class="icon-pencil"></i>');
		//}
	});

	$('a.ajax-change').on('click',function()
	{
		var xid = $(this).attr("gp_id");
		var val = $(this).attr('value').trim();
		var orgval = $(this).attr('orgval').trim();
		var grade_type = $(this).attr('grade_type');
		//console.log(orgval);
		// if(val.length >= 2 && isInt(val))
		//if(val.length >= 1)
		//{	
		
			//if(val !== orgval){
				$(this).parents('td').find('span.loading').html('<img src="'+load+'">');
				$(this).attr('orgval',val);
				//create a holder for objects
				ajaxQueueArray = [];
				run.holder($(this));
				
				// console.log(ajaxQueue);
				//loop
				$.each(ajaxQueueArray,function(i,e)
				{	
					if(e.status == 'unprocessed')
					{
						run.init(e.ajaxObject,i, "", grade_type);
					}
				});
			//}
			
		//}else{
			//$(this).parents('td').find('span.loading').html('<i class="icon-pencil"></i>');
		//}
	});
	
	function isInt(n) {
		return n % 1 === 0;
	}
});

function compute_attendance_total (kind) {

	var total = 0;

	$('.cls_'+kind).each(function(){
		total += isNaN(parseFloat($(this).val())) ? 0 : parseFloat($(this).val());
		
	})
	
	total = isNaN(total) ? 0 : total;

	$('.idt_'+kind).text(total);
}

/**
 * Compute  Final Grade
 * Get ALl Grade Total and Devide  by the number  of grade
 * Compute Only if all grades are filled up
 * Round to the 3rd decimal value
 */
function compute_final_grade (e) {
	
	var xkey = e.attr("sub_key");
	var xgp_total = $('.class_txt_grade_'+xkey).length;
	var xctr = 0;
	var xgrade_total = 0;

	$('.class_txt_grade_'+xkey).each(function() {
		var grade = parseFloat($(this).val().trim());

		if(grade){
			xgrade_total += grade;
			xctr++;
		}

	})

	if(xgp_total === xctr){
		var final_grade = xgrade_total / xctr;
		final_grade = parseFloat(final_grade).toFixed(3);
		if(!isNaN(final_grade)){
			$('#final_grade_'+xkey).text(final_grade);
			$('#final_grade_'+xkey).show();
		}
	}
}

